import {FakeRoute, type ProcessedRequest} from "vite-plugin-fake-server";
import {checkFailure, getRequestToken, resultError, resultOk} from "../util";
import type {PageResult} from "~/types/global";
import type {JobLog} from "~/types/log/jobLog";
import {pageResult, queryResult} from "../mock_data/jobLog";
import {defineFakeRoute} from "vite-plugin-fake-server/client";

/** 分页查询api */
function pageApi(): FakeRoute {
  return {
    url: '/mock-api/logs/jobLog/page',
    method: 'post',
    response: (request: ProcessedRequest) => {
      const token = getRequestToken(request)
      if (!token) {
        return resultError('未能读取到有效Token', { code: 401 })
      }

      let page = (request.body.page as number) - 1
      return resultOk<PageResult<JobLog>>(pageResult.data as unknown as PageResult<JobLog>)
    },
  }
}

/** 单体查询api */
function getApi(): FakeRoute {
  return {
    url: '/mock-api/logs/jobLog/:id',
    method: 'get',
    response: (request: ProcessedRequest) => {
      const token = getRequestToken(request)
      if (!token) {
        return resultError('未能读取到有效Token', { code: 401 })
      }

      const params = request.params
      if (!params.id) return checkFailure('id不能为空')

      const data = queryResult.data?.find(i => i.id === params.id!)
      return resultOk<JobLog>(data as unknown as JobLog)
    },
  }
}

export default defineFakeRoute([
  pageApi(),
  getApi(),
])
